function ecog = ecogValidPeaksRejData(ecog, epochstart,epochend, band, eventtype);

% finds theta peak within a time window locked to stimulus trigger
% uses ecog.trigger, which is an output of ecogCondSeparation.m.
% ecog.trigger contains timepoints where an event occured (movement or
% stimulus). 
% 
% OUTPUT: field validpeaks with the timepoints in the whole time series 
%         were the peaks of interest can be found. For example this is 
%         necessary for the comparison of theta and gamma angles after 
%         movement onset
%         
% EXAMPLE: ecog = ecogValidpeaks(ecog, 1,0,.7,1);
%          takes the ecog structure and the first column in the field
%          trigger, since this column contains after use of 
%          ecogCondSeparation(... 'movement') the timepoints of movement
%          onsets



% =========================================================================
% two new variables are used afterwards for the detection of deep peaks
% in ecog = ecogCheck4ThetaChannel(ecog)
% =========================================================================

clc;

if isfield(ecog,'validpeaks') == 1;
    ecog = rmfield(ecog,'validpeaks');
end

ecog.validpeaks = [];
% xx = [];

for k = 1:size(band,2);
for trial = 1:size(ecog.data,3);   
    % =====================================================================
    % looking for Movement onset 
    % =====================================================================
   switch eventtype
        case 'movement'
            x = find(ecog.MovOnset(:,:,trial) == max(ecog.MovOnset(:,:,trial)));
        case 'stimulus'
            x = ecog.srate;
    end

    startInd      = x(1) + round(ecog.srate * epochstart);
    endInd        = x(1) + round(ecog.srate * epochend);    
    
    for chan = 1:size(ecog.data,1);
        % =================================================================
        % looking for peaks relative to movement onset
        % =================================================================
        valids = find(( ecog.peaks{ k }( chan,:,trial ) > startInd & ...
                      ( ecog.peaks{ k }( chan,:,trial ) < endInd)));
%         xx = cat(2,xx,valids);
%         valids = [];    
        ecog.validpeaks(chan,1:length(valids),trial) = ecog.peaks{k}(chan,valids,trial);
    end

%     xx = [];
end
end

% ecog = ecogCheck4ThetaChannel(ecog,'peak');
